package com.hyt.it.ogt.kq.service.bm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.base.BaseEntity;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.exception.exception.BusinessLogicException;
import com.hyt.it.ogt.kq.common.bm.enums.BmAuditStatusEnum;
import com.hyt.it.ogt.kq.common.bm.enums.BmProjectNeedPayEnum;
import com.hyt.it.ogt.kq.common.bm.enums.BmProjectVerifyEnum;
import com.hyt.it.ogt.kq.common.bm.enums.StuStatusEnum;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.common.bm.utils.DateUtil;
import com.hyt.it.ogt.kq.common.bm.utils.RemoteUtil;
import com.hyt.it.ogt.kq.common.config.exception.InvalidRequestException;
import com.hyt.it.ogt.kq.service.bm.feign.cj.CjClient;
import com.hyt.it.ogt.kq.service.bm.feign.cj.model.ApiExamPublishInfo;
import com.hyt.it.ogt.kq.service.bm.feign.kw.KwClient;
import com.hyt.it.ogt.kq.service.bm.mapper.StudentProjectMapper;
import com.hyt.it.ogt.kq.service.bm.model.dto.ApiExamPublishInfoDTO;
import com.hyt.it.ogt.kq.service.bm.model.entity.NonOpenInfo;
import com.hyt.it.ogt.kq.service.bm.model.entity.Project;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentInfo;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentProject;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentSubject;
import com.hyt.it.ogt.kq.service.bm.model.param.GroupRegistrationExamineeInfo;
import com.hyt.it.ogt.kq.service.bm.model.param.MyExamRecordParam;
import com.hyt.it.ogt.kq.service.bm.model.param.ProjectStudentImportRecordParam;
import com.hyt.it.ogt.kq.service.bm.model.vo.*;
import com.hyt.it.ogt.kq.service.bm.mq.GroupRegistrationDataProducer;
import com.hyt.it.ogt.kq.service.bm.service.*;
import com.hyt.it.ogt.kq.service.gov.api.bm.BmApi;
import com.hyt.it.ogt.kq.service.model.vo.wechat.WeChatCandidateArrangeDetailVO;
import com.hyt.it.ogt.kq.service.model.vo.wechat.WeChatCandidateArrangeVO;
import com.hyt.loginfo.model.ExamineeRegisterVO;
import com.hyt.loginfo.model.User;
import com.hyt.progress.service.ProgressManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 考生报名表 服务实现类
 * </p>
 *
 * @author wangt
 * @since 2020-05-15
 */
@Slf4j
@Service
public class StudentProjectServiceImpl extends BaseServiceImpl<StudentProjectMapper, StudentProject> implements IStudentProjectService {

	@Resource
	private StudentProjectMapper studentProjectMapper;
	@Resource
	private KwClient kwClient;
	@Resource
	private CjClient cjClient;
	@Resource
	private IUserPermissionService iUserPermissionService;
	@Resource
	private BmApi kwGovClient;
	@Resource
	private IProjectService iProjectService;
	@Resource
	private IStudentPayService iStudentPayService;
	@Resource
	private IStudentInfoService iStudentInfoService;
	@Resource
	private IStudentSubjectService iStudentSubjectService;
    @Resource
    private GroupRegistrationDataProducer groupRegistrationDataProducer;
    @Resource
    private INonOpenService iNonOpenService; 

	@Override
	public List<StudentStatVo> statStudentByHour(ProjectParam param) throws Exception {
		Integer count = 0;
		List<StudentStatVo> resultList = new ArrayList<StudentStatVo>();

		try {
			if("0".equals(param.getState())){
				param.setStartTime(DateUtil.dateToStr(new Date())+" 00:00:00");
				param.setEndTime(DateUtil.dateToStr(new Date())+" 23:59:59");
			} else if("1".equals(param.getState())){
				param.setStartTime(DateUtil.firstDayOfWeek(new Date())+" 00:00:00");
				param.setEndTime(DateUtil.lastDayOfWeek()+" 23:59:59");
			} else if("2".equals(param.getState())){
				param.setStartTime(DateUtil.getFirstDayDateOfMonth(new Date())+" 00:00:00");
				param.setEndTime(DateUtil.getLastDayOfMonth(new Date())+" 23:59:59");
			} else {
				param.setStartTime(DateUtil.dateToStr(new Date())+" 00:00:00");
				param.setEndTime(DateUtil.dateToStr(new Date())+" 23:59:59");
			}
			ApiResponse api = kwClient.findCandidateFinishExamCount(param.getStartTime(), param.getEndTime(), param.getOfficeId(), param.getState());
			List<Object> statList = (List<Object>) api.getData();
			if("0".equals(param.getState())){
				resultList = iUserPermissionService.statStudentByHour(param);
				for(int i = 0 ; i < resultList.size(); i++){
					String hour = resultList.get(i).getTime();
					if (statList != null && statList.size() > 0) {
						for (Object obj : statList) {
							Map<String, Object> tempmap = (Map<String, Object>) obj;
							if(tempmap.get("time").toString().equals(hour)) {
								resultList.get(i).setCompleteStudentNum(Integer.valueOf(tempmap.get("studentNum").toString()));
							}
						}
					}
				}
			} else {
				resultList = iUserPermissionService.statStudentByDate(param);
				for (int i = 0; i < resultList.size(); i++) {
					String hour = resultList.get(i).getTime();
					if (statList != null && statList.size() > 0) {
						for (Object obj : statList) {
							Map<String, Object> tempmap = (Map<String, Object>) obj;
							if (hour.equals(tempmap.get("time").toString())) {
								resultList.get(i).setCompleteStudentNum(Integer.valueOf(tempmap.get("studentNum").toString()));
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		return resultList;
	}

	@Override
	public Map<String, String> getRegIdById(List<String> studentIds) {
		return this.lambdaQuery()
				.select(BaseEntity::getId, StudentProject::getRegId)
				.in(BaseEntity::getId, studentIds)
				.eq(BaseEntity::getDelFlag, Boolean.FALSE)
				.list()
				.stream()
				.filter(data -> StrUtil.isNotBlank(data.getId()))
				.filter(data -> StrUtil.isNotBlank(data.getRegId()))
				.collect(Collectors.toMap(StudentProject::getRegId, BaseEntity::getId, (oldValue, newValue) -> newValue));
	}

	@Override
	public Map<String, String> getProjectIdById(List<String> studentIds) {
		return this.lambdaQuery()
				.select(BaseEntity::getId, StudentProject::getProjectId)
				.in(BaseEntity::getId, studentIds)
				.eq(BaseEntity::getDelFlag, Boolean.FALSE)
				.list()
				.stream()
				.filter(data -> StrUtil.isNotBlank(data.getId()))
				.filter(data -> StrUtil.isNotBlank(data.getProjectId()))
				.collect(Collectors.toMap(StudentProject::getProjectId, BaseEntity::getId, (oldValue, newValue) -> newValue));
	}




	@Override
	public StudentProject getProjectStudent(String projectId, String regId) {
		if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(regId)) {
			return null;
		}
		return studentProjectMapper.getProjectStudent(projectId, regId);
	}



	@Override
	public List<StudentProject> getProjectStudents(String projectId) {
		if(StringUtils.isEmpty(projectId)) {
			return null;
		}
		return studentProjectMapper.getProjectStudents(projectId);
	}


	/**
	 * @Params:
	 * @Description:	获取考生所有考试
	 * @Author: STARF
	 * @CreateDate: 2022/5/20 10:16
	 **/
	public ApiResponse<List<WeChatCandidateArrangeVO>> getAllCandidateArrange(String officeId, String regId) {
		//组装考生studentId
		List<StudentProject> studentList = studentProjectMapper.getOfficeStudentIdList(officeId, regId);
		String sbStr = "";
		for (StudentProject studentProject: studentList) {
			if ("".equals(sbStr)) {
				sbStr = studentProject.getId();
			} else {
				sbStr = sbStr + "," + studentProject.getId();
			}
		}
		log.info("---getWeChatCandidateArrangeVO--studentId={}", sbStr);

		ApiResponse<List<WeChatCandidateArrangeVO>> response = kwGovClient.getWeChatCandidateArrangeVOByStudentIds(sbStr);
		log.info("---getWeChatCandidateArrangeVO---response={}", FastJsonUtil.getBeanToJson(response));
		return response;
	}


	/**
	 * @Params:
	 * @Description: 小程序考生考试安排列表
	 * @Author: STARF
	 * @CreateDate: 2022/1/13 15:07
	 **/
	@Override
	public List<WeChatCandidateArrangeVO> getWeChatCandidateArrangeVO(String officeId, String regId) {
		ApiResponse<List<WeChatCandidateArrangeVO>> response = getAllCandidateArrange(officeId, regId);
		if (null != response && (response.getCode() == Constant.RESPONSE_CODE_SUCCESS || response.getCode() == 30000)) {
			List<WeChatCandidateArrangeVO> list = response.getData();
			if(CollectionUtils.isNotEmpty(list)) {
				//删除已过期的考试安排
				Iterator<WeChatCandidateArrangeVO> iterator = list.listIterator();
				while (iterator.hasNext()) {
					if (iterator.next().getEndTime().isBefore(LocalDateTime.now())) {
						iterator.remove();
					}
				}
				for (WeChatCandidateArrangeVO arrange: list) {
					Project project = iProjectService.getById(arrange.getSignUpId());
					if (null != project) {
						arrange.setProjectName(project.getProjectName());
					}
					WeChatCandidateArrangeDetailVO detail = getWeChatCandidateArrangeDetailVO(arrange.getSignUpId(), arrange.getTimeId(), regId);
					if (null != detail) {
						arrange.setExamUrl(detail.getExamUrl());
						arrange.setTicket(detail.getTicket());
						arrange.setPlaceName(detail.getPlaceName());
						arrange.setPlaceAddress(detail.getPlaceAddress());
						arrange.setRoomAddress(detail.getRoomAddress());
						arrange.setSeatNumber(detail.getSeatNumber());
					}
				}
				return list;
			}
		}
		return null;
	}


	/**
	 * @Params:
	 * @Description: 小程序考生考试安排详情
	 * @Author: STARF
	 * @CreateDate: 2022/1/13 16:07
	 **/
	@Override
	public WeChatCandidateArrangeDetailVO getWeChatCandidateArrangeDetailVO(String projectId, String timeId, String regId) {
		//查找考生的studentId
		StudentProject studentProject = studentProjectMapper.getProjectStudent(projectId, regId);
		if (null == studentProject) {
			BusinessLogicException.throwException(31010110, "报名任务不存在");
		}
		log.info("----getWeChatCandidateArrangeDetailVO---studentId={}", studentProject.getId());
		ApiResponse<WeChatCandidateArrangeDetailVO> response = kwGovClient.getWeChatCandidateArrangeDetailVO(projectId, timeId, studentProject.getId());
		log.info("---getWeChatCandidateArrangeDetailVO---response={}", response);
		if (null != response && (response.getCode() == Constant.RESPONSE_CODE_SUCCESS || response.getCode() == 30000)) {
			WeChatCandidateArrangeDetailVO detail = response.getData();
			if(null != detail) {
				Project project = iProjectService.getById(projectId);
				if (null != project) {
					detail.setProjectName(project.getProjectName());
				}
				return detail;
			}
		}
		return null;
	}

	/**
	 * @Params:
	 * @Description:	获取正在开放报名的考试
	 * @Author: STARF
	 * @CreateDate: 2022/3/23 11:35
	 **/
	@Override
	public List<ProjectStatVo> getEffectivePeoject(List<ProjectStatVo> list, String regId)  throws Exception {
		if (CollectionUtils.isNotEmpty(list)) {
			for (ProjectStatVo studentProjectVo : list) {
				//考生是否已填写基本信息
				StudentProject studentProject = studentProjectMapper.getProjectStudent(studentProjectVo.getId(), regId);
				if (null != studentProject) {
					List<StudentInfoVo> studentInfoVoList = iStudentInfoService.getByStudentId(studentProjectVo.getId(), studentProject.getId());
					studentProjectVo.setHasStudentInfo(StringUtils.isNotEmpty(regId) && studentInfoVoList.size() > 0 ? 1 : 0);
				} else {
					studentProjectVo.setHasStudentInfo(0);
				}
				// 首先看下项目是不是需要缴费
				if (studentProjectVo.getIsPay().equals(1)) {
					// 查询考生是否有缴费科目
					Map<String, Object> map = iStudentPayService.queryPayInfo2(studentProjectVo.getStudentId());
					String code = (String) map.get("code");
					studentProjectVo.setStudentProjectPayStatus(code);
					studentProjectVo.setStudentProjectPayStatusDesc("待缴费");
					if ("15038".equals(code)) {
						studentProjectVo.setStudentProjectPayStatusDesc("待缴费");
					}
					if ("15046".equals(code)) {
						studentProjectVo.setStudentProjectPayStatusDesc("无需缴费");
					}
					if ("15044".equals(code)) {
						// 考生暂无需缴费科目，请勿重复缴费！
						studentProjectVo.setStudentProjectPayStatusDesc("无需缴费");
					}
					if ("15048".equals(code)) {
						// 您报名的科目暂未通过审核，请等待通过审核再进行缴费！
						studentProjectVo.setStudentProjectPayStatusDesc("无需缴费");
					}
				}else {
					studentProjectVo.setStudentProjectPayStatusDesc("无需缴费");
				}
			}
		}
		return list;
	}

    /**
     * @Params:
     * @Description: 我的报名记录
     * @Author: STARF
     * @CreateDate: 2022/3/23 11:31
     **/
    @Override
    public List<ProjectStatVo> getMyProject(String officeId, String regId) throws Exception {
        // 查询考生机构下所有的报名项目
        List<ProjectStatVo> list = iProjectService.queryStudentProjectIgnoreSubject(officeId, regId);
        if (CollectionUtils.isNotEmpty(list)) {
            LocalDateTime now = LocalDateTime.now();
            list.stream().parallel().forEach(projectStatVo -> {
                try {
                    StudentProjectInfoVo studentProjectInfoVo = iStudentInfoService.getProjectSubjectById(projectStatVo.getId(), regId);
                    // 考生是否已填写基本信息
                    List<StudentInfoVo> studentInfoVoList = iStudentInfoService.getByStudentId(projectStatVo.getId(), studentProjectInfoVo.getStudentId());
                    projectStatVo.setHasStudentInfo(CollUtil.isNotEmpty(studentInfoVoList) ? 1 : 0);
                    // 是否有缴退费记录
                    boolean hasPayRecord = false;
                    // 需要支付的科目
                    Integer needPaySub = 0;
                    // 报考科目
                    int stuSujectNum = 0;
                    StringBuilder stuSubjects = new StringBuilder();
                    for (ProjectSubjectVo projectSubjectVo : studentProjectInfoVo.getStudentSubjectList()) {
                        // 如果科目已经报考
                        if ("1".equals(projectSubjectVo.getStatus())) {
                            stuSubjects.append(projectSubjectVo.getSubjectName()).append(",");
                            stuSujectNum++;
                            if (null != projectSubjectVo.getIsPay() && 1 == projectSubjectVo.getIsPay()) {
                                needPaySub++;
                            }
                        }
                        if (null != projectSubjectVo.getIsPay() && 1 == projectSubjectVo.getIsPay() && null != projectSubjectVo.getPayStatus() && !"0".equals(projectSubjectVo.getPayStatus())) {
                            hasPayRecord = true;
                        }
                    }
                    if (stuSujectNum == 0) {
                        // 还未提交报考科目
                        if (projectStatVo.getEndTime().isBefore(now)) {
                            return;
                        }
                        projectStatVo.setStuStatus(StuStatusEnum.COMMIT.getCode());
                        projectStatVo.setStuStatusDesc("未报名");
                        projectStatVo.setStudentProjectPayStatusDesc(projectStatVo.getIsPay().equals(1) ? "未缴费" : "无需缴费");
                        projectStatVo.setActiveButton(1);
                    } else {
                        // 已提交报考科目
                        stuSubjects = stuSubjects.deleteCharAt(stuSubjects.length()-1);
                        projectStatVo.setStudentSubjects(stuSubjects.toString());

                        // 判断报名时间， 报名已经结束
                        if (projectStatVo.getEndTime().isBefore(now)) {
                            // 如果报名已经结束
                            String stuStatusDesc = getStuStatusDescAfterProjectEndTime(projectStatVo, studentProjectInfoVo);
                            projectStatVo.setStuStatusDesc(stuStatusDesc);
                            projectStatVo.setStudentProjectPayStatusDesc(hasPayRecord ? "已缴费" : "无需缴费");
                            
                            // 如果驳回
                            if (projectStatVo.getAuditState() == BmAuditStatusEnum.UNAPPROVED.getAuditStatus() || projectStatVo.getAuditState() == BmAuditStatusEnum.PENDINGAPPROVAL.getAuditStatus()) {
                                // 如果还在审核期
                                if (null != projectStatVo.getAuditEndTime() && projectStatVo.getAuditEndTime().isAfter(LocalDateTime.now())) {
                                    projectStatVo.setActiveButton(7);
                                }
                                if (null != projectStatVo.getAuditEndTime() && projectStatVo.getAuditEndTime().isBefore(LocalDateTime.now())) {
                                    projectStatVo.setActiveButton(10);
                                }
                                if (null == projectStatVo.getAuditEndTime() && projectStatVo.getEndTime().isAfter(LocalDateTime.now())) {
                                    projectStatVo.setActiveButton(hasPayRecord ? 11 : 6);
                                }
                                if (null == projectStatVo.getAuditEndTime() && projectStatVo.getEndTime().isBefore(LocalDateTime.now())) {
                                    projectStatVo.setActiveButton(10);
                                }
                            } else {
                                // 审核通过，需要缴费
                                if (projectStatVo.getAuditState() == BmAuditStatusEnum.APPROVED.getAuditStatus() && BmProjectNeedPayEnum.UNPAY.getPayStatus().equals( projectStatVo.getIsPay())) {
                                    projectStatVo.setActiveButton(hasPayRecord ? 11 : 10);
                                }
                                if (projectStatVo.getAuditState() == BmAuditStatusEnum.APPROVED.getAuditStatus() && BmProjectNeedPayEnum.PAY.getPayStatus().equals( projectStatVo.getIsPay())) {
                                    // 如果已经过了缴费时间
                                    if (null != projectStatVo.getPayEndTime() && projectStatVo.getPayEndTime().isBefore(LocalDateTime.now())) {
                                        projectStatVo.setActiveButton(hasPayRecord ? 11 : 10);
                                        if (0 == studentProjectInfoVo.getPayStatus() || 1 == studentProjectInfoVo.getPayStatus()) {
                                            projectStatVo.setStuStatusDesc("未完成报考");
                                            projectStatVo.setStudentProjectPayStatusDesc("未缴费");
                                        }
                                        if (2 == studentProjectInfoVo.getPayStatus()) {
                                            projectStatVo.setStudentProjectPayStatusDesc("已缴费");
                                        }
                                        if (3 == studentProjectInfoVo.getPayStatus()) {
                                            projectStatVo.setStudentProjectPayStatusDesc("部分退费");
                                        }
                                        if (4 == studentProjectInfoVo.getPayStatus()) {
                                            projectStatVo.setStuStatusDesc("未完成报考");
                                            projectStatVo.setStudentProjectPayStatusDesc("已退费");
                                        }
                                    }
                                    // 如果还没有过缴费时间
                                    if (null != projectStatVo.getPayEndTime() && projectStatVo.getPayEndTime().isAfter(LocalDateTime.now())) {
                                        // 如果已经缴费则显示已缴费完成报考
                                        if (2 == studentProjectInfoVo.getPayStatus()) {
                                            projectStatVo.setStudentProjectPayStatusDesc("已缴费");
                                            projectStatVo.setStuStatusDesc("完成报考");
                                            projectStatVo.setActiveButton(9);
                                        } else {
                                            projectStatVo.setStuStatusDesc("审核通过");
                                            projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                            projectStatVo.setActiveButton(8);
                                        }
                                    }
                                }
                            }
                        } else {
                            // 已有提交报考科目的状态下，审核(报考)状态与缴费状态
                            if (BmProjectVerifyEnum.UNVERIFY.getVerifyStatus().equals(projectStatVo.getIsVerify())) {
                                // 不需要审核，不需要缴费
                                if (BmProjectNeedPayEnum.UNPAY.getPayStatus().equals(projectStatVo.getIsPay())) {
                                    // 无审核无缴费
                                    projectStatVo.setStuStatusDesc("完成报考");
                                    projectStatVo.setStudentProjectPayStatusDesc("无需缴费");
                                    // 可以修改基本信息和科目
                                    projectStatVo.setActiveButton(6);
                                    // 不需要缴费按钮
                                    projectStatVo.setAuditState(0);
                                } else {
                                    // 不审核需缴费
                                    projectStatVo.setStuStatusDesc("已报考");
                                    projectStatVo.setAuditState(1);
                                    switch (studentProjectInfoVo.getPayStatus()) {
                                        case 0:
                                            projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                            projectStatVo.setActiveButton(7);
                                            break;
                                        case 1:
                                            projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                            projectStatVo.setActiveButton(7);
                                            break;
                                        case 2:
                                            projectStatVo.setStudentProjectPayStatusDesc("已缴费");
                                            projectStatVo.setActiveButton(6);
                                            break;
                                        case 3:
                                            projectStatVo.setStudentProjectPayStatusDesc("已部分退款");
                                            projectStatVo.setActiveButton(7);
                                            break;
                                        case 4:
                                            projectStatVo.setStudentProjectPayStatusDesc("已退费");
                                            projectStatVo.setActiveButton(7);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            } else {
                                // 如果需要审核,不需要缴费
                                if (BmProjectNeedPayEnum.UNPAY.getPayStatus().equals( projectStatVo.getIsPay()) || (!hasPayRecord && stuSujectNum > 0 && needPaySub == 0)) {
                                    // 需审核无缴费
                                    projectStatVo.setStudentProjectPayStatusDesc("无需缴费");
                                    // 不需要缴费按钮
                                    projectStatVo.setAuditState(0);
                                    switch (studentProjectInfoVo.getIsAudit()) {
                                        case 0:
                                            projectStatVo.setStuStatusDesc("待审核");
                                            projectStatVo.setActiveButton(4);
                                            break;
                                        case 1:
                                            projectStatVo.setStuStatusDesc("完成报考");
                                            projectStatVo.setActiveButton(5);
                                            break;
                                        case 2:
                                            projectStatVo.setStuStatusDesc("驳回");
                                            projectStatVo.setActiveButton(6);
                                            break;
                                        default:
                                            break;
                                        }
                                } else {
                                    // 需审核需缴费
                                    switch (studentProjectInfoVo.getIsAudit()) {
                                        case 0:
                                            projectStatVo.setStuStatusDesc("待审核");
                                            projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                            switch (studentProjectInfoVo.getPayStatus()) {
                                                case 0:
                                                    projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                                    break;
                                                case 1:
                                                    projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                                case 2:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已缴费");
                                                    break;
                                                case 3:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已部分退款");
                                                    break;
                                                case 4:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已退费");
                                                    break;
                                                default:
                                                    break;
                                            }
                                            projectStatVo.setActiveButton(7);
                                            projectStatVo.setAuditState(1);
                                            break;
                                        case 1:
                                            switch (studentProjectInfoVo.getPayStatus()) {
                                                case 0:
                                                    projectStatVo.setStuStatusDesc("审核通过");
                                                    projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                                    projectStatVo.setActiveButton(8);
                                                    break;
                                                case 1:
                                                    projectStatVo.setStuStatusDesc("审核通过");
                                                    projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                                    projectStatVo.setActiveButton(8);
                                                case 2:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已缴费");
                                                    projectStatVo.setStuStatusDesc("完成报考");
                                                    projectStatVo.setActiveButton(9);
                                                    break;
                                                case 3:
                                                    projectStatVo.setStuStatusDesc("审核通过");
                                                    projectStatVo.setStudentProjectPayStatusDesc("已部分退款");
                                                    projectStatVo.setActiveButton(8);
                                                    break;
                                                case 4:
                                                    projectStatVo.setStuStatusDesc("审核通过");
                                                    projectStatVo.setStudentProjectPayStatusDesc("已退费");
                                                    projectStatVo.setActiveButton(8);
                                                    break;
                                                default:
                                                    break;
                                            }
                                            break;
                                        case 2:
                                            projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                            projectStatVo.setStuStatusDesc("驳回");
                                            switch (studentProjectInfoVo.getPayStatus()) {
                                                case 0:
                                                    projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                                    break;
                                                case 1:
                                                    projectStatVo.setStudentProjectPayStatusDesc("待缴费");
                                                case 2:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已缴费");
                                                    break;
                                                case 3:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已部分退款");
                                                    break;
                                                case 4:
                                                    projectStatVo.setStudentProjectPayStatusDesc("已退费");
                                                    break;
                                                default:
                                                    break;
                                            }
                                            projectStatVo.setActiveButton(7);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                        }
                    }

                    Integer active = projectStatVo.getActiveButton();
                    // 是否允许修改报考科目
                    if (null != active && active > 2 && active < 8) {
                        projectStatVo.setAllowUpdateSub(1);
                    } else {
                        projectStatVo.setAllowUpdateSub(0);
                    }
                    // 是否显示缴退费记录
                    if (null != active && (active == 3 || active == 9 || active == 10 || active == 11) && hasPayRecord) {
                        projectStatVo.setShowPayRecord(1);
                    } else {
                        projectStatVo.setShowPayRecord(0);
                    }
                    
                    // 是否可以申请退款
                    if (null != projectStatVo.getIsRefund() && projectStatVo.getIsRefund() == 0 && null != projectStatVo.getRefuseTime() &&  projectStatVo.getRefuseTime().isAfter(LocalDateTime.now()) && hasPayRecord) {
                        projectStatVo.setAllowRefund(1);
                    }else {
                        projectStatVo.setAllowRefund(0);
                    }

                    // 无审核无缴费，报名审核时间范围内允许修改科目
                    if (null != active && active == 10) {
                        // 且报名驳回&&没有超过审核时间
                        if (null != projectStatVo.getBeginTime() && projectStatVo.getBeginTime().isBefore(LocalDateTime.now()) && null != projectStatVo.getAuditEndTime() && projectStatVo.getAuditEndTime().isAfter(LocalDateTime.now()) && projectStatVo.getAuditState() == BmAuditStatusEnum.UNAPPROVED.getAuditStatus()) {
                            projectStatVo.setAllowUpdateSub(1);
                        }
                    }
                } catch (Exception e) {
                    log.error("miniRecord----projectId={}, regId={}, e={}", projectStatVo.getId(), regId, e);
                }
            });
            list.removeIf(vo -> null == vo.getActiveButton());
        }
        return list;
    }


	/**
     * 报考结束之后，拼接显示内容
     * @param projectStatVo
     * @param studentProjectInfoVo
     * @return
     */
    private String getStuStatusDescAfterProjectEndTime(ProjectStatVo projectStatVo, StudentProjectInfoVo studentProjectInfoVo) {
        String stuStatusDesc = "完成报考";
        // 如果项目需要审核
        if(null != projectStatVo && BmProjectVerifyEnum.VERIFY.getVerifyStatus().equals(projectStatVo.getIsVerify())) {
            // 查看考生是否审核通过
            if(BmAuditStatusEnum.UNAPPROVED.getAuditStatus().equals(studentProjectInfoVo.getIsAudit())) {
                stuStatusDesc = "驳回";
            }
            // 查看考生是否审核通过
            if(BmAuditStatusEnum.PENDINGAPPROVAL.getAuditStatus().equals(studentProjectInfoVo.getIsAudit())) {
                stuStatusDesc = "待审核";
            }
        }
        return stuStatusDesc;
    }

    @Override
	public List<StudentExamRecordVo> myExamRecord(MyExamRecordParam param){
		// 获取用户准考证、考试ID
		List<WeChatCandidateArrangeVO> WeChatCandidateArrangeVOs = Optional.ofNullable(getAllCandidateArrange(param.getOfficeId(), param.getRegId()))
				.filter(RemoteUtil::isSuccess)
				.map(ApiResponse::getData)
				.orElseGet(Lists::newArrayList);

		// 组装请求参数
		List<ApiExamPublishInfo> examPublishInfos = WeChatCandidateArrangeVOs.stream()
				.map(data -> ApiExamPublishInfo.builder()
						.examId(data.getTimeId())
						.admissionNo(data.getAdmissionNumber())
						.build())
				.collect(Collectors.toList());

		// 考生考试信息获取
		List<ApiExamPublishInfoDTO> apiExamPublishInfoDTOS = Optional.ofNullable(cjClient.getExamPublishInfoVos(examPublishInfos))
				.filter(RemoteUtil::isSuccess)
				.map(ApiResponse::getData)
				.orElseGet(Lists::newArrayList);

		// 封装请求数据
		List<StudentExamRecordVo> examRecordVos = apiExamPublishInfoDTOS.stream()
				.filter(ApiExamPublishInfoDTO::getPublishStatus)
				.map(data -> {
					StudentExamRecordVo studentExamRecordVo = BeanUtil.toBean(data, StudentExamRecordVo.class);
					studentExamRecordVo.setExamId(data.getId())
							.setExamName(data.getExamName())
							.setBeginTime(data.getExamStartDay())
							.setEndTime(data.getExamEndDay())
							.setAdmissionNo(data.getAdmissionNo())
							.setSubjectName(data.getSubjectName())
							.setQualifiedStatusName(data.getExamResult())
							.setAllScore(data.getResultScore())
							.setReviewStatus(data.getReviewStatus())
							.setExamineeId(data.getExamineeId());
					return studentExamRecordVo;
				}).collect(Collectors.toList());

		return examRecordVos;
	}

	@Override
	public Optional<Integer> countAreaEnrolledNum(String projectId, String areaCollectInfoId, String areaCode, String deptId) {
		return studentProjectMapper.countAreaEnrolledNum(projectId, areaCollectInfoId, areaCode, deptId);
	}

	@Override
	public Optional<Integer> countAreaPendingNum(String projectId, String areaCollectInfoId, String areaCode, String deptId) {
		return studentProjectMapper.countAreaPendingNum(projectId, areaCollectInfoId, areaCode, deptId);
	}

	@Override
	public Optional<Integer> countAreaPassAuditNum(String projectId, String areaCollectInfoId, String areaCode, String deptId) {
		return studentProjectMapper.countAreaPassAuditNum(projectId, areaCollectInfoId, areaCode, deptId);
	}

	@Override
	public Optional<Integer> countAreaFailAuditNum(String projectId, String areaCollectInfoId, String areaCode, String deptId) {
		return studentProjectMapper.countAreaFailAuditNum(projectId, areaCollectInfoId, areaCode, deptId);
	}

	@Override
	public Optional<Integer> countAreaUnpaidNum(String projectId, String areaCollectInfoId, String areaCode, String deptId) {
		return studentProjectMapper.countAreaUnpaidNum(projectId, areaCollectInfoId, areaCode, deptId);
	}

	@Override
	public Optional<Integer> countAreaPaidNum(String projectId, String areaCollectInfoId, String areaCode, String deptId) {
		return studentProjectMapper.countAreaPaidNum(projectId, areaCollectInfoId, areaCode, deptId);
	}


	@Override
	public Optional<Integer> countEnrolledNum(String projectId, String deptId) {
		return studentProjectMapper.countEnrolledNum(projectId, deptId);
	}

	@Override
	public Optional<Integer> countPendingNum(String projectId, String deptId) {
		return studentProjectMapper.countPendingNum(projectId, deptId);
	}

	@Override
	public Optional<Integer> countPassAuditNum(String projectId, String deptId) {
		return studentProjectMapper.countPassAuditNum(projectId, deptId);
	}

	@Override
	public Optional<Integer> countFailAuditNum(String projectId, String deptId) {
		return studentProjectMapper.countFailAuditNum(projectId, deptId);
	}

	@Override
	public Optional<Integer> countUnpaidNum(String projectId, String deptId) {
		return studentProjectMapper.countUnpaidNum(projectId, deptId);
	}

	@Override
	public Optional<Integer> countPaidNum(String projectId, String deptId) {
		return studentProjectMapper.countPaidNum(projectId, deptId);
	}

	@Override
	public void checkHasStudent(String projectId) {
		List<StudentProject> studentProjects = this.getProjectStudents(projectId);
		if (CollectionUtils.isNotEmpty(studentProjects)) {
			throw new InvalidRequestException(Constant.RESPONSE_CODE_31051008);
		}
	}

    @Override
	public StudentProject getProjectStudentById(String studentId) {
		return studentProjectMapper.getProjectStudentById(studentId);
	}

	/**
	 * 当考生付款或退款时计算pay值给bm_student_project
	 * @param
	 */
	@Override
	public void ansycSubjectPayStatus(List<StudentSubject> subjectList){
		if(CollectionUtils.isEmpty(subjectList)){
			return;
		}
		StudentSubject studentSubject = subjectList.get(0);
		String studentId = studentSubject.getStudentId();
		String projectId = studentSubject.getProjectId();
		//查出来bm_student_project表
		StudentProject studentProject = this.baseMapper.selectById(studentId);
		if(Objects.isNull(studentProject)){
			log.error("# ansycSubjectPayStatus,studentId:【{}】,projectId：【{}】",studentId,projectId);
			return;
		}

		//第二步：查出来这个考生有多少要缴费的项目
		QueryWrapper<StudentSubject> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(StudentSubject::getStudentId, studentId)
				.eq(StudentSubject::getProjectId,projectId).eq(StudentSubject::getDelFlag,Boolean.FALSE)
				.select(StudentSubject::getPay,StudentSubject::getIsPay);
		List<StudentSubject> list = iStudentSubjectService.list(wrapper);
		//需要支持的项目
		long needPayNum = list.stream().filter(e -> Objects.equals(1, e.getIsPay())).count();
		//已成功支持的项目
		long payNum = list.stream().filter(e -> Objects.equals(1, e.getPay())).count();

		Integer payStatus = 0;
		if(needPayNum != 0L && payNum != 0L && payNum < needPayNum){
			//部分支持
			payStatus = 1;
		} else if (needPayNum != 0L && payNum != 0L && payNum >= needPayNum){
			payStatus = 2;
		}
		//第三步 更新bm_student_project表
		StudentProject updateEntity = new StudentProject();
		updateEntity.setId(studentProject.getId());
		updateEntity.setPay(payStatus);
		this.updateById(updateEntity);
	}

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchSaveImportData(String projectId,List<ImportStudentDataVO> importStudentDataVOList, ProjectStudentImportRecordParam recordParam, Boolean createFlag, User currentLoginUser) {
        List<StudentProject> studentProjects = importStudentDataVOList.stream()
                .map(ImportStudentDataVO::getStudentProject)
                .collect(Collectors.toList());

        List<StudentInfo> studentInfos = importStudentDataVOList.stream()
                .map(ImportStudentDataVO::getStudentInfo)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());

        List<StudentSubject> studentSubjects = importStudentDataVOList.stream()
                .map(ImportStudentDataVO::getStudentSubject)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
        
        List<String> identificationNos = importStudentDataVOList.stream()
                .map(ImportStudentDataVO::getIdentificationNo)
                .collect(Collectors.toList());

        this.saveBatch(studentProjects);
        ProgressManager.updateProgressCurrent(94, "考生报名信息入库完成");

        iStudentInfoService.saveBatch(studentInfos);
        ProgressManager.updateProgressCurrent(95, "考生报名采集信息入库完成");

        iStudentSubjectService.saveBatch(studentSubjects);
        ProgressManager.updateProgressCurrent(96, "考生科目信息入库完成");
        
        // 更新报名资格状态
        if (CollUtil.isNotEmpty(identificationNos)) {
            UpdateWrapper<NonOpenInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(NonOpenInfo::getProjectId, projectId).in(NonOpenInfo::getCardNumber, identificationNos).set(NonOpenInfo::getIsBm, true);
            iNonOpenService.update(updateWrapper);
        }

        // 如果创建账号
        if (createFlag) {
            log.debug("[集体报名][文件录入][创建账号] 创建集合大小size:[{}]", importStudentDataVOList.size());
            for (int i = 0; i < importStudentDataVOList.size(); i++) {
                ImportStudentDataVO importStudentDataVO = CollUtil.get(importStudentDataVOList, i);
                StudentProject studentProject = importStudentDataVO.getStudentProject();

                GroupRegistrationExamineeInfo groupRegistrationExamineeInfo = new GroupRegistrationExamineeInfo();
                groupRegistrationExamineeInfo.setStudentId(studentProject.getId());

                ExamineeRegisterVO examineeRegisterVO = iStudentInfoService.createExamineeRegisterVO(currentLoginUser.getOfficeid(), recordParam, importStudentDataVO.getStudentInfoData());
                groupRegistrationExamineeInfo.setExamineeRegisterVO(examineeRegisterVO);

                log.info("[集体报名][文件录入][创建账号] sendMessage:[{}]", FastJsonUtil.getBeanToJson(groupRegistrationExamineeInfo));
                groupRegistrationDataProducer.sendMessage(groupRegistrationExamineeInfo);
                log.info("[集体报名][文件录入][创建账号] sendMessage success");
            }
        }
    }

}
